import {defineStore} from "pinia";
import {ref} from "vue";
import type {UserBrowseHistory} from "@/types/user";

export const useBrowsingHistoryStore = defineStore('browsingHistory', () => {
        const browsingHistory = ref<UserBrowseHistory[]>([])

        /**
         *  添加浏览历史
         * @param history 历史数据
         */
        const addBrowsingHistory = (history: UserBrowseHistory) => {
            // 检查是否已存在该历史记录
            if (browsingHistory.value.length >= 1) {
                browsingHistory.value = browsingHistory.value.filter((item) => item.id !== history.id)
            }
            browsingHistory.value.unshift(history) //将该历史提前，并修改其时间
        }
        /**
         *   清除浏览历史
         *   @param ids 需要清除的历史记录的id
         */
        const clearBrowsingHistory = (ids: string[]) => {
            browsingHistory.value = browsingHistory.value.filter(item => !ids.includes(item.id))
        }
        const clearAllBrowsingHistory = () => {
            browsingHistory.value = []
        }

        return {
            browsingHistory,
            addBrowsingHistory,
            clearBrowsingHistory,
            clearAllBrowsingHistory
        }
    },
    {
        persist: {
            storage: {
                setItem(key, value) {
                    uni.setStorageSync(key, value)
                },
                getItem(key) {
                    return uni.getStorageSync(key)
                },
            },
        },
    }
)